import { SAVE_USER_INFO, CLEAR_USER_INFO, INIT_USER_INFO, GET_USER_INFO } from '__STORE__/operation-type';
import Cookie from 'vue-cookie'
import { show } from '__SERVICE__/user.js'
//初始化死数据
const initDeadUserInfo = {
  user_id: '', access_token: ''
}

//初始化或数据
const initAliveUserInfo = {
  nickname: '',
  avatar_url: '',
  email: '',
  cover_url: '',
  gender: '1',
  motto: ''
}

const state = ()=>({
  deadUserInfo: Object.assign({}, initDeadUserInfo), //数据会更新，但是不会影响页面变化
  aliveUserInfo: Object.assign({}, initAliveUserInfo),
})

const getters = {
  
}

const mutations = {
  [SAVE_USER_INFO](state, payload) {
    const {deadUserInfo, aliveUserInfo} = payload
    if(deadUserInfo) { // 更新需要更新的
      Object.assign(state.deadUserInfo, deadUserInfo)
    }
    if(aliveUserInfo) {
      Object.assign(state.aliveUserInfo, aliveUserInfo)
    }
    Cookie.set('deadUserInfo', JSON.stringify(state.deadUserInfo), {expires: 7}); //设置cookie
    Cookie.set('aliveUserInfo', JSON.stringify(state.aliveUserInfo), {expires: 7}); //设置cookie
  },

  [CLEAR_USER_INFO](state, payload) {
    state.deadUserInfo = initDeadUserInfo
    state.aliveUserInfo = initAliveUserInfo
    Cookie.delete('deadUserInfo'); //删除对应cookie
    Cookie.delete('aliveUserInfo'); //删除对应cookie
  },
}

const actions = {
  [SAVE_USER_INFO](context, payload) {
    const {commit, state} = context;
    const deadUserInfo = {} // 存储死信息
    const aliveUserInfo = {} // 存储活信息

    for(let pro in initDeadUserInfo) {
      if(pro in payload) deadUserInfo[pro] = payload[pro]; //遍历，过滤变量属性
    }
    
    for(let pro in initAliveUserInfo) {//遍历传来的对象
      if(pro in payload)  aliveUserInfo[pro] = payload[pro]; //遍历，过滤变量属性
    }
    //提交action的副作用
    commit(SAVE_USER_INFO, {deadUserInfo, aliveUserInfo});
  },

  [CLEAR_USER_INFO](context, payload) {
    const {commit, state} = context;
    //提交action的副作用
    commit(CLEAR_USER_INFO);
  },

  //初始化
  [INIT_USER_INFO](context, payload) {
    const {commit, state} = context;
    const deadUserInfo = {} // 存储死信息
    const aliveUserInfo = {} // 存储活信息
    Object.assign(deadUserInfo, initDeadUserInfo, JSON.parse(Cookie.get('deadUserInfo')))
    Object.assign(aliveUserInfo, initAliveUserInfo, JSON.parse(Cookie.get('aliveUserInfo')))
    //提交action的副作用
    commit(SAVE_USER_INFO, {deadUserInfo, aliveUserInfo});
  },

  //获取个人信息
  async [GET_USER_INFO]({commit, state, dispatch}, payload) {
    const {access_token, user_id: id} = state.deadUserInfo
    try {
      const result = await show({access_token, id})
      const {data: {user}} = result
      const {avatar_url, nickname,motto, email, cover_url, gender } = user // 只存储 access_token 和 id
      dispatch(SAVE_USER_INFO, {
        avatar_url, nickname, motto, email, cover_url, gender, access_token: user.access_token
      })
    }catch(e) {
      const {messageAuthor, message} = e
      console.log(message)
    }
  }
}

const user = {
  state,
  mutations,
  getters,
  actions
};

export default user;